package com.qdsg.ysg.doctor.nurse.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.ui.WebViewActivity;
import com.qdsg.ysg.doctor.ui.adapter.ExtraListAdapter;
import com.qdsg.ysg.doctor.ui.adapter.NurseInfoAdapter;
import com.qdsg.ysg.doctor.ui.adapter.NurseItemsAdapter;
import com.qdsg.ysg.doctor.ui.dialog.AddExtraDialog;
import com.qdsg.ysg.doctor.ui.dialog.CancelOrderDialog;
import com.qdsg.ysg.doctor.util.TimeUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.PatientProjectDTO;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilList;

/**
 * Description
 * Created by lbj on 2022/4/9 15:02
 */
public class AtyAcceptDetail extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_look_record)
    TextView tvLookRecord;
    @BindView(R.id.tv_person_name)
    TextView tvPersonName;
    @BindView(R.id.tv_person_sex)
    TextView tvPersonSex;
    @BindView(R.id.tv_person_age)
    TextView tvPersonAge;
    @BindView(R.id.tv_person_tel)
    TextView tvPersonTel;
    @BindView(R.id.tv_person_address)
    TextView tvPersonAddress;
    @BindView(R.id.tv_person_time)
    TextView tvPersonTime;
    @BindView(R.id.cl_address)
    ConstraintLayout clAddress;
    @BindView(R.id.rv_info)
    RecyclerView rvInfo;
    @BindView(R.id.rv_items)
    RecyclerView rvItems;
    @BindView(R.id.rv_extra)
    RecyclerView rvExtra;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.tv_extra)
    TextView tvExtra;
    @BindView(R.id.tv_history)
    TextView tvHistory;
    @BindView(R.id.tv_cancel_nurse)
    TextView tvCancelNurse;
    @BindView(R.id.tv_edit_time)
    TextView tvEditTime;
    @BindView(R.id.cl_extra)
    ConstraintLayout clExtra;
    List<String> mInfoList = new ArrayList<>();
    List<String> mItemList = new ArrayList<>();
    Map<String, List<PatientProjectDTO.NaAdditionalConsumablesDTO>> mExtraList = new HashMap<>();
    List<String> mKeyList = new ArrayList<>();

    String appointmentId, orderId, diagnoseId, patientId;
    private Boolean isFullScroll = false;
    private NurseInfoAdapter nurseInfoAdapter;
    private NurseItemsAdapter nurseItemsAdapter;
    private ExtraListAdapter extraListAdapter;


    @Override
    protected int getLayoutResource() {
        return R.layout.aty_accept_detail;
    }

    @Override
    protected void initData() {
        appointmentId = getIntent().getStringExtra( "appointmentId" );
        if (!UtilString.isEmpty( appointmentId )) {
            appointmentDetail();
        }
    }


    @Override
    protected void initViews() {
        tvTitle.setText( "订单详情" );
        LinearLayoutManager managerInfo = new LinearLayoutManager( mContext );
        managerInfo.setOrientation( LinearLayoutManager.VERTICAL );
        rvInfo.setLayoutManager( managerInfo );
        LinearLayoutManager manager = new LinearLayoutManager( mContext );
        manager.setOrientation( LinearLayoutManager.VERTICAL );
        rvItems.setLayoutManager( manager );
        LinearLayoutManager managerExtra = new LinearLayoutManager( mContext );
        managerExtra.setOrientation( LinearLayoutManager.VERTICAL );
        rvExtra.setLayoutManager( managerExtra );
        nurseInfoAdapter = new NurseInfoAdapter( mContext, mInfoList );
        rvInfo.setAdapter( nurseInfoAdapter );
        nurseItemsAdapter = new NurseItemsAdapter( mContext, mItemList );
        rvItems.setAdapter( nurseItemsAdapter );
        extraListAdapter = new ExtraListAdapter( mContext, mExtraList, mKeyList, true );
        rvExtra.setAdapter( extraListAdapter );
        extraListAdapter.setOnItemClickLitener( this::cancelConsumables );

    }

    @OnClick({R.id.tv_look_record, R.id.tv_extra, R.id.tv_history, R.id.tv_cancel_nurse, R.id.tv_edit_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_extra:
                showAddExtraDialog();
                break;
            case R.id.tv_look_record:
            case R.id.tv_history:
                Bundle bundleHistory = new Bundle();
                bundleHistory.putString( "patientId", patientId );
                bundleHistory.putString( "fromWhere", "CloudListActivity" );
                startActivity( WebViewActivity.class, bundleHistory );
                break;
            case R.id.tv_cancel_nurse:
                showCancelOrderDialog();
                break;
            case R.id.tv_edit_time: //修改预约时间
                initTimePicker();
                break;
        }
    }

    private void showAddExtraDialog() {
        AddExtraDialog mAddExtraDialog = AddExtraDialog.newInstance( appointmentId );
        mAddExtraDialog.show( getSupportFragmentManager(), "AddExtraDialog" );
        mAddExtraDialog.setmListener( () -> {
            isFullScroll = true;
            appointmentDetail();
        } );
    }


    private void showCancelOrderDialog() {
        CancelOrderDialog mCancelOrderDialog = CancelOrderDialog.newInstance( appointmentId, "1" );
        mCancelOrderDialog.show( getSupportFragmentManager(), "CancelOrderDialog" );
        mCancelOrderDialog.setmListener( conclusion -> finish() );
    }


    private void appointmentDetail() {
        RestProxy.getInstance().appointmentDetail( appointmentId, new Observer<PatientProjectDTO>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PatientProjectDTO patientProjectDTO) {
                try {
                    patientId = patientProjectDTO.data.patientId;
                    orderId = patientProjectDTO.data.orderId;
                    tvPersonName.setText( "姓名：" + patientProjectDTO.data.patientName );
                    tvPersonSex.setText( "性别：" + patientProjectDTO.data.sex );
                    tvPersonAge.setText( "年龄：" + patientProjectDTO.data.age + "岁" );
                    tvPersonAddress.setText( "地址：" + patientProjectDTO.data.adress );
                    tvPersonTime.setText( "预约时间：" + patientProjectDTO.data.appointmentTime );
                    tvPersonTel.setText( "联系方式：" + patientProjectDTO.data.patientPhone );
                    String isSetOut = patientProjectDTO.data.isSetOut;
                    if ("1".equals( isSetOut )) {
                        tvEditTime.setVisibility( View.GONE );
                    } else {
                        tvEditTime.setVisibility( View.VISIBLE );
                    }
                    mInfoList.clear();
                    if ("1".equals( patientProjectDTO.data.isEyeRed )) {
                        mInfoList.add( "眼睛是否红、肿、痛：是" );
                    } else {
                        mInfoList.add( "眼睛是否红、肿、痛：否" );
                    }
                    if ("1".equals( patientProjectDTO.data.isSecretion )) {
                        mInfoList.add( "有无分泌物：有分泌物" );
                    } else {
                        mInfoList.add( "有无分泌物：无分泌物" );
                    }
                    if ("1".equals( patientProjectDTO.data.isTrichiasis )) {
                        mInfoList.add( "睫毛有无倒睫：有倒睫" );
                    } else {
                        mInfoList.add( "睫毛有无倒睫：无倒睫" );
                    }
                    if ("1".equals( patientProjectDTO.data.isUnobstructed )) {
                        mInfoList.add( "泪道是否通畅：通畅" );
                    } else {
                        mInfoList.add( "泪道是否通畅：不通畅" );
                    }
                    if ("1".equals( patientProjectDTO.data.isSuture )) {
                        mInfoList.add( "眼部是否有缝线：有缝线" );
                        mInfoList.add( "缝线位置：" + patientProjectDTO.data.suturePosition );
                        if ("1".equals( patientProjectDTO.data.isRemove )) {
                            mInfoList.add( "是否需要拆线：需要" );
                        } else {
                            mInfoList.add( "是否需要拆线：不需要" );
                        }

                    } else {
                        mInfoList.add( "眼部是否有缝线：无缝线" );
                    }
                    nurseInfoAdapter.notifyDataSetChanged();

                    mItemList.clear();
                    mItemList.add( patientProjectDTO.data.projectTitle );
                    nurseItemsAdapter.notifyDataSetChanged();
                    //耗材信息
                    List<PatientProjectDTO.NaAdditionalConsumablesDTO> consumeMaterials = patientProjectDTO.data.consumeMaterials;
                    if (!UtilList.isEmpty( consumeMaterials )) {
                        clExtra.setVisibility( View.VISIBLE );
                        mExtraList.clear();
                        mKeyList.clear();
                        Map<String, List<PatientProjectDTO.NaAdditionalConsumablesDTO>> collect = consumeMaterials.stream().collect( Collectors.groupingBy( PatientProjectDTO.NaAdditionalConsumablesDTO::getOrderId ) );
                        mExtraList.putAll( collect );
                        for (Map.Entry<String, List<PatientProjectDTO.NaAdditionalConsumablesDTO>> entry : collect.entrySet()) {
                            String key = entry.getKey();
                            mKeyList.add( key );
                        }

                        extraListAdapter.notifyDataSetChanged();
                        if (isFullScroll) {
                            new Handler().postDelayed( () -> {
                                nestedScrollView.fullScroll( ScrollView.FOCUS_DOWN );//滚动到底部

                            }, 500 );
                        }

                    } else {
                        clExtra.setVisibility( View.GONE );
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {

            }
        } );

    }

    private void cancelConsumables(String orderId) {
        RestProxy.getInstance().cancelConsumables( orderId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                appointmentDetail();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    /**
     * 时间选择器
     *
     * @time 2021/1/7 9:27
     */
    private void initTimePicker() {//Dialog 模式下，在底部弹出
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get( Calendar.YEAR );
        int month = calendar.get( Calendar.MONTH );
        int day = calendar.get( Calendar.DAY_OF_MONTH );
        calendar.set( year, month, day );
        Calendar endDate = Calendar.getInstance();
        endDate.set( 2031, 0, 1 );

        TimePickerView pvTime = new TimePickerBuilder( this, (date, v) -> updateTime( TimeUtil.getSystemTime( date ) ) )
                .setTimeSelectChangeListener( date -> Log.i( "pvTime", "onTimeSelectChanged" ) )
                .setDate( selectedDate )
                .setRangDate( calendar, endDate )
                .setType( new boolean[]{true, true, true, true, true, false} )
                .isDialog( true ) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener( view -> Log.i( "pvTime", "onCancelClickListener" ) )
                .setLineSpacingMultiplier( 2.0f )
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM );

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams( params );

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations( com.bigkoo.pickerview.R.style.picker_view_slide_anim );//修改动画样式
                dialogWindow.setGravity( Gravity.BOTTOM );//改成Bottom,底部显示
                dialogWindow.setDimAmount( 0.3f );
            }
        }
        pvTime.show();
    }

    private void updateTime(String systemTime) {
        RestProxy.getInstance().updateTime( appointmentId, systemTime, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                appointmentDetail();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        // TODO: add setContentView(...) invocation
        ButterKnife.bind( this );
    }
}
